package com.kerrykidz.system.util.sync;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;

import org.springframework.stereotype.Component;

import com.kerrykidz.system.util.SystemParaSingleton;

@Component("syncFileConsumer")
public class SyncFileConsumer implements SyncConsumer {

	@Override
	public void doConsumer(Serializable message) {
		@SuppressWarnings("unchecked")
		HashMap<String, List<FileMessage>> fileMessage = (HashMap<String, List<FileMessage>>) message;
		for (String key : fileMessage.keySet()) {
			String path = SystemParaSingleton.getInstance().getValue(key);
			File dic = new File(path);
			if (!dic.exists())
				dic.mkdirs();
			for (FileMessage fm : fileMessage.get(key)) {
				File fil = new File(path + File.separator + fm.getFileName());
				if (!fil.exists()) {
					OutputStream os = null;
					try {
						fil.createNewFile();
						os = new FileOutputStream(fil);
						os.write(fm.getBytes());
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						try {
							os.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}

				}
			}
		}
	}

}
